package encryption

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"crypto/sha256"
	"encoding/base64"
	"encoding/hex"
)

// PKCS7Padding填充
func PKCS7Padding(ciphertext []byte, blockSize int) []byte {
	padding := blockSize - len(ciphertext)%blockSize
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(ciphertext, padtext...)
}

// 加密函数
func AesEncrypt(plaintext []byte, key []byte, iv []byte) (string, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return "", err
	}
	//判断加密快的大小
	blockSize := block.BlockSize()
	//填充
	encryptBytes := PKCS7Padding(plaintext, blockSize)
	//初始化加密数据接收切片
	crypted := make([]byte, len(encryptBytes))
	//使用cbc加密模式
	blockMode := cipher.NewCBCEncrypter(block, iv)
	//执行加密
	blockMode.CryptBlocks(crypted, encryptBytes)

	// Base64编码
	return base64.StdEncoding.EncodeToString(crypted), nil
}

// Sha256
func Sha256(text string) string {
	hash := sha256.Sum256([]byte(text))
	hexHash := hex.EncodeToString(hash[:])
	return hexHash
}

// PKCS7UnPadding去除填充
func PKCS7UnPadding(data []byte, blockSize int) []byte {
	length := len(data)
	unpadding := int(data[length-1])

	return data[:length-unpadding]
}

// 解密函数
func AesDecrypt(ciphertext string, key []byte, iv []byte) ([]byte, error) {
	data, err := base64.StdEncoding.DecodeString(ciphertext)
	if err != nil {
		return nil, err
	}

	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}

	mode := cipher.NewCBCDecrypter(block, iv)
	mode.CryptBlocks(data, data)

	// 去除PKCS7Padding
	data = PKCS7UnPadding(data, block.BlockSize())
	data = bytes.Trim(data, "\x00")

	return data, nil
}

func GetDataAes(key string, text string) string {
	key_sha := Sha256(key)
	de_key := key_sha[10:26]
	iv := Sha256(de_key)[20:36]
	key_byte := []byte(de_key)
	iv_byte := []byte(iv)
	ret_byte, err := AesDecrypt(text, key_byte, iv_byte)
	if err != nil {
		return ""
	}
	return string(ret_byte)
}

func SetDataAes(key string, text string) string {
	key_sha := Sha256(key)
	de_key := key_sha[10:26]
	iv := Sha256(de_key)[20:36]
	key_byte := []byte(de_key)
	iv_byte := []byte(iv)
	text_byte := []byte(text)
	ret_str, err := AesEncrypt(text_byte, key_byte, iv_byte)

	if err != nil {
		return ""
	}
	return ret_str
}
